package io.qytc.jboot.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.qytc.jboot.entity.License;
import io.qytc.jboot.utils.Security.RSAUtils;

import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

public class LicenseUtils {

    static String basepath = LicenseUtils.class.getClassLoader().getResource("").getPath();

    /**
     * 读文件
     * @param name
     * @return
     */
    public static String readFile(String name){
        File file = new File(basepath + "/" + name);
        if(!file.exists()){
            return "";
        }
        try {
            String res = "";
            FileInputStream fin = new FileInputStream(file);
            byte[] buffer = new byte[fin.available()];
            //读入流,保存在byte数组
            fin.read(buffer);
            res = new String(buffer,"ISO-8859-1");
            //关闭流
            fin.close();
            return res;
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 写文件
     * @param name  文件名
     * @param content   内容
     * @return
     */
    public static boolean writeFile(String name, String content){
        File file = new File(basepath + "/" + name);
        if(file.exists()){
            file.delete();
        }
        try {
            FileOutputStream fout = new FileOutputStream(file,false);
            byte[] bytes = content.getBytes("ISO-8859-1");
            for (int i = 0; i < bytes.length; i++) {
                fout.write(bytes[i]);
            }
            fout.flush();
            fout.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 生成licenses 文件
     * @param license
     * @throws Exception
     */
    public static boolean generateLicense(License license, String currentTime) throws Exception {
        String name = "/upload/license/license" +currentTime+".lic";
        File file=new File(basepath + "/upload/license");
        if (!file.exists()){
            file.mkdirs();
        }
        String publicKey = readFile("rsa_public_key.pem");
        try {
            String jsonObject = JSONObject.toJSONString(license);
            byte[] data = jsonObject.getBytes("ISO-8859-1");
            byte[] encodedData = RSAUtils.encryptByPublicKey(data, publicKey);
            String encodedStr = new String(encodedData,"ISO-8859-1");
            return writeFile(name,encodedStr);
        }catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取license
     * @return License
     * @throws Exception
     */
    public static License getLicense() {
        try{
            File file = new File(basepath + "/upload/license");
            if(!file.exists()){
                return null;
            }
            File license=null;
            File[] files = file.listFiles();
            if(files!=null && files.length>0){
                license= Objects.requireNonNull(file.listFiles())[0];
            }
            else {
                return null;
            }
            String privateKey = readFile("pkcs8_private_key.pem");
            String res = readFile("/upload/license/" +license.getName());
            byte[] decodedData = RSAUtils.decryptByPrivateKey(res.getBytes("ISO-8859-1"), privateKey);
            String target = new String(decodedData);
            License license1 =  JSON.parseObject(target,License.class);
            return license1;
        }catch (Exception ex){
            ex.printStackTrace();
            return null;
        }
    }

    /**
     * 删除License
     * @return
     */
    public static boolean deleteLicense() {
        if(LicenseUtils.class.getClassLoader().getResource("upload/license")==null){
            return true;
        }
        File file = new File(LicenseUtils.class.getClassLoader().getResource("upload/license").getPath());
        for(File f : Objects.requireNonNull(file.listFiles())){
            f.delete();
        }
        return true;
    }

    /**
     * 生成 SN
     * @return
     */
    public static boolean generateSN(){
        File folder=new File(basepath + "/io/qytc/admin/utils/Security/");
        if(!folder.exists()){
            folder.mkdirs();
        }
        File file = new File(folder.getPath()+"/sn");
        if(file.exists()){
            file.delete();
        }
        System.err.println(basepath);
        return writeFile("/io/qytc/admin/utils/Security/sn","SN"+System.currentTimeMillis());
    }

    /**
     * 获取 SN
     * @return
     */
    public static String getSN(){
        return readFile("/io/qytc/admin/utils/Security/sn");
    }

    /**
     * 判断license 是否有效
     */
    public static boolean isLicenseValid() throws Exception {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date currentDate = df.parse(DateUtils.getStringDate());
        License license = LicenseUtils.getLicense();
        if (null == license){
            return false;
        }
        String sn = LicenseUtils.getSN();
        if (!sn.equals(license.getSerialNumber())){
            return false;
        }
        if (1 == license.getPrivilege()){
            return true;
        }
        Date deadLine = df.parse(license.getDeadLine());
        if (deadLine.getTime() < currentDate.getTime()){
            return false;
        }
        return true;
    }

    /**
     * 判断是否可发短信
     * @return
     */
    public static boolean isEnableSMS(){
        try {
            License license = LicenseUtils.getLicense();
            if (null == license){
                return false;
            }
            if (1 == license.getSmsEnable()){
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
